package com.mdd.front.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.member.Member;
import com.mdd.common.entity.user.User;
import com.mdd.common.mapper.member.MemberMapper;
import com.mdd.common.mapper.team.TeamMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.StringUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.front.service.IMemberService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.member.MemberAuthValicate;
import com.mdd.front.validate.member.MemberExamineValicate;
import com.mdd.front.validate.member.MemberSearchValidate;
import com.mdd.front.vo.member.MemberListedVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
public class MemberServiceImpl implements IMemberService {

    @Resource
    MemberMapper memberMapper;

    @Resource
    TeamMapper teamMapper;

    @Resource
    UserMapper userMapper;

    @Override
    public void memberApply(MemberAuthValicate valicate) {
        apply(valicate,"member","社团成员",1);
    }

    @Override
    public void adminApply(MemberAuthValicate valicate){
        apply(valicate,"admin","社团管理员",2);
    }


    public void apply(MemberAuthValicate valicate,String roleCode,String roleName,Integer type) {
        List<Member> member1 = memberMapper.selectList(new LambdaQueryWrapper<Member>().eq(Member::getUserId, valicate.getUserId()).eq(Member::getRoleCode, roleCode));
        if(CollectionUtils.isNotEmpty(member1)&&member1.size()>0){

        }else{
            Member member = new Member();
            BeanUtils.copyProperties(valicate,member);
            member.setRoleCode(roleCode);
            member.setRoleName(roleName);
            member.setType(type);
            member.setStatus(0);
            memberMapper.insert(member);
        }
    }

    @Override
    public PageResult<MemberListedVo> list(PageValidate pageValidate, MemberSearchValidate validate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        MPJQueryWrapper<Member> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper.selectAll(Member.class)
                .like(StringUtils.isNotEmpty(validate.getName()),"t.name",validate.getName())
                .like(StringUtils.isNotEmpty(validate.getStudentNum()),"t.student_num",validate.getStudentNum())
                .like(StringUtils.isNotEmpty(validate.getCollege()),"t.college",validate.getCollege())
                .like(StringUtils.isNotEmpty(validate.getContact()),"t.contact",validate.getContact())
                .eq(ObjectUtils.isNotEmpty(validate.getStatus()),"t.status",validate.getStatus())
                .innerJoin("(SELECT lt.* FROM la_team lt where lt.id in (select team_id from la_team_member ltm where ltm.team_id = lt.id) or lt.owner_id = "+validate.getUserId()+") ltt on ltt.name = t.college")
                .orderByDesc("id");

        IPage<Member> iPage = memberMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<MemberListedVo> list = new LinkedList<>();
        for(Member item : iPage.getRecords()) {
            MemberListedVo vo = new MemberListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public void memberExamine(MemberExamineValicate valicate) {
        Member model = memberMapper.selectOne(
                new QueryWrapper<Member>()
                        .eq("id", valicate.getId())
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        model.setStatus(valicate.getStatus());
        memberMapper.updateById(model);
        if(model.getStatus()==1){
            User user = userMapper.selectById(model.getUserId());
            if(ObjectUtils.isNotEmpty(user)){
                if(user.getSex()==null){
                    user.setSex(model.getSex());
                }
                if(StringUtils.isEmpty(user.getRealName())){
                    user.setRealName(model.getName());
                    user.setNickname(model.getName());
                }
                if(StringUtils.isEmpty(user.getAvatar())){
                    user.setAvatar(model.getCover());
                }
                user.setMobile(model.getContact());
                userMapper.updateById(user);
            }
        }
    }

    @Override
    public MemberListedVo detail(Integer userId) {
        Member member = memberMapper.selectOne(new LambdaUpdateWrapper<Member>().eq(Member::getUserId, userId));
        MemberListedVo vo = new MemberListedVo();
        if(ObjectUtils.isNotEmpty(member)) {
            BeanUtils.copyProperties(member, vo);
        }
        return vo;
    }
}
